package cn.wolfcode.wolf2w.resolver;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.myannotation.UserAunntion;
import cn.wolfcode.wolf2w.redis.service.IRedisService;
import cn.wolfcode.wolf2w.redis.test.RedisByKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

public class UserArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private IRedisService redisService;
    //指定解析器能解析的参数类型,该方法里面的注解时区分在进行保存和编辑操作以及其他接口的操作解析。
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType()==UserInfo.class&&methodParameter.hasParameterAnnotation(UserAunntion.class);
    }
    //当第一个方法返回为true时，才执行本方法，解析当前登录用户对象类型参数，获取当前用户对象信息，并注入
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest nativeRequest = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = nativeRequest.getHeader("token");
        String join = RedisByKey.USER_TOKEN.join(token);
        return redisService.getRedis(join);
    }
}
